function reply()
{
	scroll_to_input('textarea_buttons');
	$('#topic_content').focus();
}
function new_topic()
{
	scroll_to_input('textarea_buttons');
	$('#topic_title').focus();
}
function quote(post_number)
{
	// topic_content_submit topic_content_label
	var user_name = $("#quote_post"+post_number).find(".quote_name").text();
	var quote_text = $("#quote_post"+post_number).find(".quote_text").text();
	var value = $("#topic_content").val();
	var t = "";
	while(t != quote_text)
	{
		t = quote_text;
		quote_text = quote_text.replace("[br]","\n");
	}
	$("#topic_content").val(value+"[quote=#"+post_number+" "+user_name+"]"+quote_text+"[/quote]\n").focus();
	var text_length =$("#topic_content").val().length;
	$("#topic_content").caret(text_length,text_length);
	update_textarea_height("topic_content");
	scroll_to_input("textarea_buttons");
}
function scroll_to_input(id)
{
	var window_scroll = $('#'+id).offset().top + $('#'+id).outerHeight() - $(window).height() + 10;
	$(document).scrollTop(window_scroll);
}
function update_textarea_height(id)
{
	// Disabled for the time being...
	/*
	var scroll_height = document.getElementById(id).scrollHeight;
	var too_small = parseInt($("#"+id).css("height")) < scroll_height;
	var too_high = parseInt($("#"+id).css("height")) > scroll_height + 20 &&  parseInt($("#"+id).css("height")) > 150 ;
	if(too_small || too_high)
	{
		$("#"+id).css("height",scroll_height+"px");
	}
	$("#"+id).scrollTop(scroll_height);
	*/
}
function like_post(post_id,like_type)
{
	var current_value = $("#like_post"+post_id).attr("current_value");
	$("#like_buttons"+post_id).html(get_loading_img());
	$.post("/ajax/forum_like.ajax.php",{"post_id":post_id,"like_type":like_type,"current_value":current_value},function(data){
		if(data != null)
		{
			if(like_type == 1)
			{
				var likes = parseInt($("#like_post"+post_id).find(".positive").html());
				$("#like_post"+post_id).find(".positive").html(likes+1).show();
			}
			else
			{
				var likes = parseInt($("#like_post"+post_id).find(".negative").html());
				$("#like_post"+post_id).find(".negative").html(likes+1).show();
			}
			$("#like_buttons"+post_id).hide();
		}
	},"json");
}
function style_quotes()
{
	$(".quote_text").css("display", "none");
	$(".quote").each(function(){
		$(this).click(function(){
			$(this).children(".quote_text").slideToggle(200);
		});
	});
}

function forum_apply_membership(conference_id)
{
	modal.html("<div class='std'><h2 >"+pagecontent[131]+"</h2><label for=\"apply_message\">"+pagecontent[132]+" ("+pc_replace(pagecontent[133],{"[count]":"<span id='apply_message_chars'>250</span>"})+")</label><br /><textarea id=\"apply_message\" name=\"apply_message\" onkeyup='chars_left(\"apply_message_chars\",255,\"apply_message\")' rows=\"6\" cols=\"50\" class='emboss'></textarea><input type=\"hidden\" id=\"apply_id\" value=\""+conference_id+"\" /><div class=\"msgbuttons\">"+make_button(global_content["send"],"apply_send()")+" "+make_button(global_content["cancel"],"modal.hide()")+"</div></div>");
	modal.show();
	emboss();
}

function apply_send(conference_id)
{
	if($("#apply_message").val() == "")
	{
		$("#apply_message").before("<p class='error'>"+pagecontent[134]+"</p>");
		return false;
	}
	var val = $("#apply_message").val();
	var apply_id = $("#apply_id").val();
	modal.transition(get_loading_img(),function(){
		$.post("/ajax/forum_apply_conference.ajax.php",{"message":val,"conference_id":apply_id},function(data){
			var html = "<h2 >"+pagecontent[131]+"</h2>";
			if(data == "true")
			{
				html += pagecontent[135],"check";
			}
			else
			{
				html += pagecontent[136],"fail";
			}
			html += "<div class=\"msgbuttons\">"+make_button(global_content["ok"],"modal.hide()")+"</div>";
			modal.html(html).banner();
		});
	});
}

function application_reply(response,conference_id,user_id)
{
	$("#application_"+user_id).html(get_loading_img());
	$.post("/ajax/forum_apply_conference_response.ajax.php",{"conference_id":conference_id,"user_id":user_id,"response":response},function(data){
		if(data == "true")
		{
			if(response == 1) $("#application_"+user_id).html("  <img src='/pics/mini_green_check.png' /> "+pagecontent[137]);
			else if(response == 2) $("#application_"+user_id).html(" <img src='/pics/small_red_x.png' /> "+pagecontent[138]);
		}
		else
		{
			$("#application_"+user_id).html(" <span class='error'>Error</span>");
		}
	});
}
function pop_preview()
{
	modal.html(get_loading_img()).show();
	var text = $("#topic_content").val();
	$.post("/ajax/forum_preview.ajax.php",{"text":text},function(data){
		if(data != null)
		{
			var $div = $("<div />").addClass("post_preview");
			if($("#topic_title").val() != "")
			{
				$("<h1>").addClass("mega_headline topic_header").appendTo($div).html($("#topic_title").val());
			}
			var $post = $("<div />").addClass("topic_post background_gradient");
			var $user = $("<div />").addClass("user dark").appendTo($post).append(data["logo"]+"<div>"+data["name"]+"</div>"+"<div>"+data["flag"]+" "+data["pro"]+"</div><em>"+pagecontent[139]+"</em>");
			var $text = $("<div />").addClass("text").html(data["text"]).wrap("<div class=\"content\" />").parent().appendTo($post);
			modal.outer().css({
				"width":"806px"
			});
			var $actions = $("<div />").addClass("actions").append('<div class="post_number">#?</div><div class="post_time">'+data["time"]+'</div><div class="">Likes: 0</div>').appendTo($post);
			$post.append("<div class=\"clear\" />");
			var $buttons = $("<div />").addClass("textarea_buttons background_gradient");
			$buttons.html('<span onclick="submit_forum_post()" onkeypress="submit_forum_post()" class="button forum_submit_button"><span class="button_border">'+pagecontent[93]+'</span></span>')
				.append('<span onclick="modal.hide()" onkeypress="modal.hide()" class="button"><span class="button_border">'+global_content["cancel"]+'</span></span>');
			// Append
			$div.append($post).append($buttons);
			modal.outer().addClass("no_background");
			modal.html($div);
			modal.reposition();

		}
	},"json");
}

function add_bbcode(type,value)
{
	var $elem = $("#topic_content");
	if(value == "get_value")
	{
		value = $("#bbc_code_value").val();
	}
	switch(type)
	{
		case "bold":
			toggle_bbtag("b",$elem);
			break;
		case "italic":
			toggle_bbtag("i",$elem);
			break;
		case "color":
			if (value != null)
			{
				toggle_bbtag("color",$elem,value);
			}
			break;
		case "smiley":
			if (value != null)
			{
				insert_bbtag("smiley",$elem,value);
			}
			break;
		case "player":
			if(value != null)
			{
				insert_bbtag("player",$elem,value)
			}
			modal.hide();
			break;
		case "list":
			toggle_bbtag("list",$elem);
//			toggle_bb_list($elem);
			break;
		case "pre":
			toggle_bbtag("pre",$elem);
			break;
		case "image":
			if(value != null)
			{
				insert_bbtag("img",$elem,value)
			}
			modal.hide();
			break;
		case "link":
			if(value != null)
			{
				var marked = $elem.caret().text;
				if(marked.length > 0) toggle_bbtag("url",$elem,value);
				else insert_bbtag("url",$elem,value);
			}
			modal.hide();
			break;
		default:
			return false;
	}
	update_textarea_height($elem.attr("id"));
}
function prompt_value(type)
{
	if(type == "player")
	{
		var $div = $("<div style=\"padding:15px\" class=\"\" />").html("<label for=\"bbc_code_value\">"+pagecontent[130]+" </label><input type=\"text\" id=\"bbc_code_value\" tabindex='-1' class='emboss'/>");
		var $buttons = $("<div />").addClass("textarea_buttons").appendTo($div);
			$buttons.html('<span onclick="javascript:add_bbcode(\'player\',\'get_value\')" class="button"><span class="button_border">'+global_content[508]+'</span></span>')
				.append('<span onclick="javascript:modal.hide()" class="button"><span class="button_border">'+global_content["cancel"]+'</span></span>');
		modal.html($div).show();
		setTimeout(function(){$("#bbc_code_value").focus()},210);
//		modal.banner();
	}
	else if(type == "image")
	{
		var $div = $("<div style=\"padding:15px\" class=\"\" />").html("<label for=\"bbc_code_value\">"+pagecontent[128]+" </label><input type=\"text\" id=\"bbc_code_value\" class='emboss' onkeydown='check_http_bg(this)'  style='width:300px'/>");
		var $buttons = $("<div />").addClass("textarea_buttons").appendTo($div);
			$buttons.html('<span onclick="javascript:add_bbcode(\'image\',\'get_value\')" class="button"><span class="button_border">'+global_content[508]+'</span></span>')
				.append('<span onclick="javascript:modal.hide()" class="button"><span class="button_border">'+global_content["cancel"]+'</span></span>');
		modal.html($div).show();
		setTimeout(function(){$("#bbc_code_value").focus()},210);
//		modal.banner();
	}
	else if(type == "link")
	{
		var $div = $("<div style=\"padding:15px\" class=\"\" />").html("<label for=\"bbc_code_value\">"+pagecontent[129]+" </label><input type=\"text\" id=\"bbc_code_value\" class='emboss' onkeydown='check_http_bg(this)' style='width:300px' />");
		var $buttons = $("<div />").addClass("textarea_buttons").appendTo($div);
			$buttons.html('<span onclick="javascript:add_bbcode(\'link\',\'get_value\')" class="button"><span class="button_border">'+global_content[508]+'</span></span>')
				.append('<span onclick="javascript:modal.hide()" class="button"><span class="button_border">'+global_content["cancel"]+'</span></span>');
		modal.html($div).show();
		setTimeout(function(){$("#bbc_code_value").focus()},210);
//		modal.banner();
	}
	emboss();
}
function check_http_bg(el)
{
	if($(el).val() == "")
	{
		$(el).addClass("url_bg");
	}
	else
	{
		$(el).removeClass("url_bg");
	}
}

function toggle_color_picker()
{
	if($('#color_picker').is(":hidden"))
	{
		$('#color_picker').show().css({
			"top":($("#color_picker_button").position().top)+"px",
			"left":($("#color_picker_button").position().left)+"px"
		});
		$('#color_picker').attr("tabindex",-1).focus();
		$('#color_picker').focusout(function(){
			setTimeout(function(){
				$('#color_picker').hide();
			},100);
		});
	}
	else
	{
	//	$('#color_picker').hide();
	}
}
function toggle_smiley_picker()
{
	if($('#smiley_picker').is(":hidden"))
	{
		$('#smiley_picker').show().css({
			"top":($("#smiley_picker_button").position().top)+"px",
			"left":($("#smiley_picker_button").position().left)+"px"
		});
		$('#smiley_picker').attr("tabindex",-1).focus();
		$('#smiley_picker').focusout(function(){
			setTimeout(function(){
				$('#smiley_picker').hide();
			},100);
		});
	}
	else
	{
	//	$('#color_picker').hide();
	}
}
function insert_bbtag(tag,$elem,value)
{
	var val = $elem.val();
	var start = $elem.caret().start;
	var start_text = val.substring(0,start);
	var end_text = val.substring($elem.caret().start);
	var text = "["+tag+(value != null?"="+value:"")+"]";
	if(tag == "url") text+= value+"[/"+tag+"]";
	$elem.val(start_text+text+end_text);
	$elem.caret(start,start+text.length);
}
function toggle_bbtag(tag,$elem,value)
{
	var add_length = 0;
	var add_value ="";
	if(value != null)
	{
		var add_length = value.length+1;
		var add_value = "="+value;
	}
	var val = $elem.val();
	var marked = $elem.caret().text;
	var add_ln = tag == "list" ? "\n":"";
	var start_chars = tag == "list" ? 3 : 2;

	if(marked.substring(0,tag.length+add_length+2) == "["+tag+add_value+"]" && marked.substring(marked.length-tag.length-3) == "[/"+tag+"]") var text = marked.substring(tag.length+start_chars,marked.length-tag.length-start_chars-1);
	else var text = "["+tag+add_value+"]"+add_ln+marked+add_ln+"[/"+tag+"]";

	var start = $elem.caret().start;
	var start_text = val.substring(0,start);
	var end_text = val.substring($elem.caret().end);
	$elem.val(start_text+text+end_text);
	$elem.caret(start,start+text.length);
}
function submit_forum_post()
{
	button_disable($(".forum_submit_button"));
	$('#topic_content_submit').click();
//	$("#forum_post_form").submit();
	modal.hide();
}

function get_likes(post_id)
{
	$.post("/ajax/forum_like.ajax.php",{"get_likes" : post_id},function(data){
		if(data != null)
		{
			var $text = $("<div />").html("Likes: <br />");
			if(data.length == 0)
			{
				$text.html("Likes: None");
			}
			else
			{
				for(var i in data)
				{
					if(data[i]["user"])
					{
						var like = eval(data[i]["like"]);
						$text.append(data[i]["user"]["club_name"]+": <span style='color:"+(like > 0 ? "#090" : "#900")+"'>"+data[i]["like"]+"<span> <span class='gray'>#"+data[i]["user_id"]+"</span><br>");
					}
				}
			}
			$("#tooltip").html($text);
		}
	},"json");

}
function pop_likes(post_id)
{
	$.post("/ajax/forum_like.ajax.php",{"get_likes" : post_id},function(data){
		if(data != null)
		{
			var $text = $("<div />").html("Likes: <br />");
			if(data.length == 0)
			{
				$text.html("Likes: None");
			}
			else
			{
				for(var i in data)
				{
					if(data[i]["user"])
					{
						var like = eval(data[i]["like"]);
						$text.append("<a href='/club/"+data[i]["user_id"]+"/' class='normal'>"+data[i]["user"]["club_name"]+"</a> <span class='"+(like>0?"positive":"negative")+"' >"+data[i]["like"]+"</span><br>");
					}
				}
			}
			modal.html($text).show();
		}
	},"json");

}

function pop_conference_members(conference_id)
{
	$.post("/ajax/forum_conference_info.ajax.php",{"get":"members","conference_id":conference_id},function(data){
		if(data != null)
		{
			var html = "";
			for(var i in data["members"])
			{
				var m = data["members"][i];
				if(m)
				{
					html += "<div>"+get_club_link({"club":{"id":m["user_id"],"name":m["club_name"],"country":m["country"]},"flag":true})+" "+m["pro"]+" " +m["league"]+"</div>";
				}
			}
			if(html == "") html = pagecontent[140];
			html += "<div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()")+"</div>";
			modal.html("<h2>"+pagecontent[141]+"</h2>"+html);
			modal.show();
		}
	},"json");
}

function pop_conference_applications(conference_id)
{
	$.post("/ajax/forum_conference_info.ajax.php",{"get":"applications","conference_id":conference_id},function(data){
		if(data != null)
		{
			var html = "";
			for(var i in data["applications"])
			{
				var m = data["applications"][i];
				if(m)
				{
					html += "<div>"+get_club_link({"club":{"id":m["user_id"],"name":m["club_name"],"country":m["country"]},"flag":true})+" "+m["pro"]+" " +m["league"];
					if(m["status"] == 0)
					{
						html += "<span id='application_"+m["user_id"]+"'> "+make_button(pagecontent[144],"application_reply(1,"+conference_id+","+m["user_id"]+")");
						html += " "+make_button(pagecontent[143],"application_reply(2,"+conference_id+","+m["user_id"]+")")+"</span>";
						html += "<br />"+pagecontent[142]+" "+m["message"];
						html += "<br /><span class='subtle'>"+pagecontent[177]+" "+m["applied"]+"</span>";
					}
					else if(m["status"] == 1)
					{
						html += "  <img src='/pics/mini_green_check.png' /> "+pagecontent[137];
					}
					else if(m["status"] == 2)
					{
						html += " <img src='/pics/small_red_x.png' /> "+pagecontent[138];
					}
					html += "</div>";
				}
			}
			if(html == "") html = pagecontent[145];
			html += "<div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()")+"</div>";
			modal.html("<h2>"+pagecontent[178]+"</h2>"+html);
			modal.show();
		}
	},"json");
}
function pop_create_conference(lang)
{
	languages = languages || {};
	var html = "";
		html += '<h2>'+pagecontent[147]+'</h2>';
		html += create_conference_html("","",lang,0);
		html += "<div class='msgbuttons'>";
		html += make_button(global_content["create"],"submit_form('create_conf_submit')")+" ";
		html += make_button(global_content["cancel"],"modal.hide()")+" ";
		html += "</div>";
	modal.html(html);
	modal.show();
	$("#new_conference_language").selectmenu({
		"style":"dropdown",
		"width":"200",
		"maxHeight":"250"
	});
	make_radio("public_conference");
	emboss();
}
function update_conference_info(conf_id)
{
	var name = $("#new_conference_name").val();
	var description = $("#new_conference_description").val();
	var language = $("#new_conference_language").val();
	var priv = $("[name=is_private]:checked").val();
	modal.transition(get_loading_img(),function(){
		$.post("/ajax/forum_conference_info.ajax.php",{"get":"update","name":name,"description":description,"language":language,"private":priv,"conference_id":conf_id},function(data){
			if(data != null)
			{
				if(data["succes"] == 1)
				{
					modal.html("<h2>"+pagecontent[148]+"</h2><p>"+pagecontent[149]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
					body_refresh();
				}
				else
				{
					modal.html("<h2>"+pagecontent[148]+"</h2><p class='error'>"+pagecontent[150]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
				}
			}
		},"json");
	});
}
function pop_edit_conference(conf_id)
{
	var conf = forum_content["conference"];
	languages = languages || {};
	var html = "";
		html += '<h2>'+pagecontent[148]+'</h2>';
		html += create_conference_html(conf["name"],conf["description"],conf["language"],conf["is_private"]);
		html += "<div class='msgbuttons'>";
		html += make_button(global_content["save"],"update_conference_info("+conf_id+")")+" ";
		html += make_button(global_content["cancel"],"modal.hide()")+" ";
		html += "</div>";
	modal.html(html);
	modal.show();
	$("#new_conference_language").selectmenu({
		"style":"dropdown",
		"width":"200",
		"maxHeight":"250"
	});
	make_radio("public_conference");
	emboss();
}
function create_conference_html(name,description,language,is_private)
{
	languages = languages || {};
	var $languages = $('<select id="new_conference_language" name="new_conference_language">');
	for(var i in languages)
	{
		var la = languages[i];
		if(la)
		{
			var sel = i == language ? " selected":"";
			$languages.append('<option value="'+i+'"'+sel+'>'+la+'</option>');
		}
	}
	var html = $('<form method="post" action="" onsubmit="true" id="create_conf_submit">').append(
		$('<label for="new_conference_name">').html(pagecontent[151]),
		$('<input type="text" id="new_conference_name" name="new_conference_name" class="emboss" value="'+name+'"/>'),
		$("<br />"),
		$('<label for="new_conference_description">').html(pagecontent[152]),
		$('<textarea id="new_conference_description" class="emboss" name="new_conference_description" rows="8" cols="50">').html(description),
		$("<br />"),
		$('<label for="new_conference_language">').html(pagecontent[153]),
		$languages,
		$("<br />"),
		$('<input type="radio" value="0" name="is_private" id="public_conference" class="less_space" '+(is_private == 0 ? "checked":"")+'/>'),
		$('<label for="public_conference">').html(pagecontent[154]),
		$('<input type="radio" value="1" name="is_private" id="private_conference" class="less_space" '+(is_private == 1 ? "checked":"")+'/>'),
		$('<label for="private_conference">').html(pagecontent[155]),
		$('<input type="hidden" name="submit_post" value="Create" />')

	);
	return $("<div />").html(html).html();
}
function pop_conference_invite(conf_id)
{
	str = "<h2>"+pagecontent[156]+"</h2>";
	str += "<div id='change_league'>"
			+global_content["club_name_or_id"]
			+'<span class="large bold" id="conference_invite_club_show" style="display:none"></span>'
			+'<input type="text" id="conference_invite_club" onkeyup="suggest_clubs(5,\'conference_invite_club\')" style="width:300px" class="emboss"/>'
			+'<input type="hidden" id="conference_invite_club_href" value="javascript:conference_invite_club_select" />'
			+'<br /><label for="conference_invite_text">'+pagecontent[142]+'</label><br /><textarea class="emboss" rows="6" id="conference_invite_text" cols="50"></textarea>'
			+'<div id="suggest_clubs_content"></div>'
			+'</div>';
	str += '<div class="msgbuttons">'+make_button(global_content["send"],"conference_invite("+conf_id+")")+' ' +make_button(global_content["cancel"],"modal.hide()")+'</div>';

	modal.html(str);
	modal.show();
	emboss();
	$("#conference_invite_club").focus();
}
function conference_invite_club_select(club_id,suggestion_id)
{
	var name = $("#suggestion_id_"+suggestion_id).html();
	$("#conference_invite_club").blur().val(club_id).hide();
	$("#conference_invite_text").focus();
	$("#conference_invite_club_show").html(name).css("cursor","pointer").show().unbind().click(function(){
		$("#conference_invite_club").show().focus();
		$(this).hide();
	});
}
function conference_invite(conf_id)
{
	var club_id = $("#conference_invite_club").val();
	var text = $("#conference_invite_text").val();
	modal.transition(get_loading_img(),function(){
		$.post("/ajax/forum_conference_info.ajax.php",{"get":"invite","club_id":club_id,"text":text,"conference_id":conf_id},function(data){
			if(data != null)
			{
				if(data["succes"] == 1)
				{
					modal.html("<h2>"+pagecontent[156]+"</h2><p>"+pagecontent[179]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
					body_refresh();
				}
				else
				{
					modal.html("<h2>"+pagecontent[156]+"</h2><p class='error'>"+pagecontent[157]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
				}
			}
		},"json");
	});
}
function join_conference(conf_id)
{
	modal.html(get_loading_img());
	modal.show();
	$.post("/ajax/forum_conference_info.ajax.php",{"get":"join","conference_id":conf_id},function(data){
		if(data != null)
		{
			if(data["succes"] == 1)
			{
				modal.html("<h2>"+pagecontent[158]+"</h2><p>"+pagecontent[159]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
				body_refresh();
			}
			else
			{
				modal.html("<h2>"+pagecontent[158]+"</h2><p class='error'>"+pagecontent[136]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
			}
		}
	},"json");
}

function leave_conference(conf_id)
{
	modal.html(get_loading_img());
	modal.show();
	$.post("/ajax/forum_conference_info.ajax.php",{"get":"leave","conference_id":conf_id},function(data){
		if(data != null)
		{
			if(data["succes"] == 1)
			{
				modal.html("<h2>"+pagecontent[160]+"</h2><p>"+pagecontent[161]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
				body_refresh();
			}
			else
			{
				modal.html("<h2>"+pagecontent[160]+"</h2><p class='error'>"+pagecontent[136]+"</p><div class='msgbuttons'>"+make_button(global_content["ok"],"modal.hide()"));
			}
		}
	},"json");
}

function pop_delete_post(post_id)
{
	var html = "<h2>"+pagecontent[162]+"</h2><p>"+pagecontent[163]+"</p>";
	html += "<div class='msgbuttons'>"+make_button(pagecontent[109],"delete_post("+post_id+")")+" "+make_button(global_content["cancel"],"modal.hide()")+"</div>";
	modal.html(html).show();
}
function delete_post(post_id)
{
	modal.html(get_loading_img());
	$.post("/ajax/forum_edit_post.ajax.php",{"post_id":post_id,"type":"delete"},function(data){
		if(data != null)
		{
			var height = $("#post"+post_id).height();
			$("#post"+post_id).animate({
				"height":"20px"
			},200,function(){
				var $html = $("<div class='deleted_post' />").html($(this).html());
				$(this).html("<div class='align_center deleted_post_text'>"+pagecontent[180]+" <span class='faux_link' onclick='undo_delete_post("+post_id+")'>"+pagecontent[181]+"</span></div>");
				$html.appendTo(this).hide();
			}).attr("orig_height",height);
			modal.hide();
		}
	},"json");
}
function undo_delete_post(post_id)
{
	$.post("/ajax/forum_edit_post.ajax.php",{"post_id":post_id,"type":"undelete"},function(data){
		if(data != null)
		{
			//$("#post"+post_id).css("height","auto").html($("#post"+post_id).find(".deleted_post").html());
			$("#post"+post_id).html($("#post"+post_id).find(".deleted_post").html());
			$("#post"+post_id).animate({
				"height":$("#post"+post_id).attr("orig_height")+"px"
			},200);
		}
	},"json");
}
function lock_topic(topic_id)
{
	$.post("/ajax/forum_edit_post.ajax.php",{"topic_id":topic_id,"type":"lock"},function(data){
		if(data != null)
		{
			page_refresh();
		}
	},"json");
}
function unlock_topic(topic_id)
{
	$.post("/ajax/forum_edit_post.ajax.php",{"topic_id":topic_id,"type":"unlock"},function(data){
		if(data != null)
		{
			page_refresh();
		}
	},"json");
}
function pin_topic(topic_id)
{
	$.post("/ajax/forum_edit_post.ajax.php",{"topic_id":topic_id,"type":"pin"},function(data){
		if(data != null)
		{
			page_refresh();
		}
	},"json");
}
function unpin_topic(topic_id)
{
	$.post("/ajax/forum_edit_post.ajax.php",{"topic_id":topic_id,"type":"unpin"},function(data){
		if(data != null)
		{
			page_refresh(); // could be something else...
		}
	},"json");
}
// Forum Ban
function pop_forum_ban(user_id,post_id,topic_url)
{
	topic_url=topic_url||document.location.pathname;
	modal.html(get_loading_img()).show();
	$.post("/ajax/forum_ban.ajax.php",{"user_id":user_id,"type":"get"},function(data){
		if(data != null)
		{
			var club_name = data["club"]["club_name"];
			var html = "<h2>"+pc_replace(pagecontent[165],{"[club]":club_name})+"</h2>"
				+"<p class='bold'>"+pagecontent[166]+"</p>";
			if(data["bans"][0] == undefined)
			{
				html += "<p class='subtle'>"+pagecontent[167]+"</p>";
			}
			else
			{
				html += "<ul style='padding: 0; margin: 0 0 0 20px;'>";
				for(var i in data["bans"])
				{
					var ban = data["bans"][i];
					if(ban)
					{
						if(ban["is_warning"])
						{
							html += "<li><span class='text_orange'>"+pagecontent[168]+"</span>: "+ban["ban_end_time"]+"<br /><span class='subtle'>"+ban["ban_reason"]+"</span></li>";
						}
						else
						{
							if(ban["still_banned"])
							{
								var red_x = ban["ban_delete"] ? "<img src='/pics/small_red_x.png' class='faux_link' title='"+global_content["delete"]+"' onclick='delete_forum_ban("+ban["id"]+","+user_id+","+post_id+",\""+topic_url+"\")'/>" : "";
								html += "<li><span class='bold'><span class='text_red'>"+ban["ban_lenght"]+"</span> - "+pagecontent[169]+" "+ban["ban_end_time"]+"</span> "+red_x+"<br /><span class='subtle'>"+ban["ban_reason"]+"</span></li>";
							}
							else
							{
								html += "<li><span class='text_red'>"+ban["ban_lenght"]+"</span> - "+pagecontent[170]+" "+ban["ban_end_time"]+"<br /><span class='subtle'>"+ban["ban_reason"]+"</span></li>";
							}
						}
					}
				}
				html += "</ul>";
			}
//			html += "<hr />";
			// tabs
			html += make_tabs([{"id":"ban_user_tab","title":pagecontent[174]},{"id":"warn_user_tab","title":pagecontent[168]}], "ban_tabs");
			// tabs content
			html +="<div class='tabs_content'>";
			// ban tab
			html += "<div id='ban_user_tab'>";
			html += "<div class='align_center'><label for='ban_period'>"+pc_replace(pagecontent[171],{"[club]":club_name})+"</label><br /><select id='ban_period'>";
			for(var i in data["ban_periods"])
			{
				var period = data["ban_periods"][i];
				if(period)
				{
					var sel = i == 2 ? " selected" : "";
					html += "<option value='"+i+"'"+sel+">"+period+"</option>";
				}
			}
			html += "</select></div>";
			html += "<label for='ban_reason'>"+pagecontent[198]+"</label><br /><textarea rows='4' cols='50' id='ban_reason' name='ban_reason' class='emboss'></textarea><br />";
			html += "<label for='ban_pm'>"+pc_replace(pagecontent[173],{"[club]":club_name})+"</label><br /><textarea rows='4' cols='50' id='ban_pm' name='ban_pm' class='emboss'></textarea>";
			html += "<div class='msgbuttons'>"+make_button(pagecontent[174],"post_forum_ban("+user_id+",'ban','"+topic_url+"',"+post_id+")")+" "+make_button(global_content["cancel"],"modal.hide()")+"</div>";
			html += "</div>";
			// warning tab
			html += "<div id='warn_user_tab'>";
			html += "<label for='warning_text'>"+pc_replace(pagecontent[173],{"[club]":club_name})+"</label><br /><textarea rows='4' cols='50' id='warning_text' name='warning_text' class='emboss'></textarea><br />";
			html += "<div class='msgbuttons'>"+make_button(pagecontent[175],"post_forum_ban("+user_id+",'warning','"+topic_url+"',"+post_id+")")+" "+make_button(global_content["cancel"],"modal.hide()")+"</div>";
			html	+= "</div>";
			// tabs content end
			html += "</div>";
			modal.html(html);
			$("#ban_period").selectmenu({
				"width":"200",
				"maxHeight":"250",
				"style":"dropdown"
			});
			emboss();
			activate_tabs($("#ban_tabs"));
			$("#ban_tabs").parent().css({"width":"500px","margin":"0 -8px"});

		}
	},"json");
}
function post_forum_ban(user_id,type,topic_url,post_id)
{
	var warning_text = $("#warning_text").val();
	var ban_pm_text = $("#ban_pm").val();
	var ban_reason = $("#ban_reason").val();
	var ban_days = $("#ban_period").val();
	modal.html(get_loading_img());
	$.post("/ajax/forum_ban.ajax.php",{"type":type,"user_id":user_id,"warning":warning_text,"ban_pm":ban_pm_text,"ban_reason":ban_reason,"ban_days":ban_days,"topic_url":topic_url,"post_id":post_id},function(data){
		if(data != null)
		{
			pop_forum_ban(user_id,post_id,topic_url);
		}
	},"json");
}
function delete_forum_ban(ban_id,user_id,post_id,topic_url)
{
	$.post("/ajax/forum_ban.ajax.php",{"type":"ban_delete","ban_id":ban_id},function(data){
		if(data["success"])
		{
			pop_forum_ban(user_id,post_id,topic_url);
		}
	},"json");
}
function make_tabs(ar, id)
{
	// Makes tabs - needs <div class='tabs_content'> with objects with id's from ar
	var html = "";
	html += "<div class='tabs_outer'><div class='tabs outer' id='"+id+"'>";
	for(var i in ar)
	{
		var tab = ar[i];
		if(tab) html += "<div tab_active='"+tab["id"]+"' id='tab"+tab["id"]+"'><div>"+tab["title"]+"</div></div>";
	}
	html += "</div></div>";
	return html;
}
function activate_tabs($tabs)
{
		// NEW Tabs
		$tabs.find("*:first").addClass("active_tab");			// Activate first tab
		// Tabs On Click Event
		$tabs.parent().siblings(".tabs_content").children().hide();
		$tabs.parent().siblings(".tabs_content").find(":first-child").show();	// ... Then show first tab content
		$tabs.children().click(function() {
			if ($(this).attr("tab_active")) {
				$(this).siblings().removeClass("active_tab");	// Remove any "active" class
				$(this).addClass("active_tab");					// Add "active" class to selected tab
				var activeTab = $(this).attr("tab_active");		// Find the set_active attribute value to identify the active tab + content

				$("#"+activeTab).siblings().hide();				// Hide all tab content
				$("#"+activeTab).show();						// Show tab
			}
		});
		// If tab is set as selected, click it!
		$tabs.find("[selected]").click();
}

function start_search()
{
	var q = $("#search").val();
	if(q != "") window.location = "/forum/search/"+q+"/";
	return false;
}
function delete_conference(id,confirm)
{
	if(!confirm)
	{
		modal.html($("<div />").append(
			$("<h2>").text("Delete conference"),
			$("<p>").text("Are you sure you wish to delete this conference?"),
			$("<div />").addClass("msgbuttons").append(
				make_button(global_content["delete"],"delete_conference("+id+",true)"),
				make_button(global_content["cancel"],"modal.hide()")
				)
		)).show();
	}
	else
	{
		modal.inner().find(".loading").remove();
		modal.inner().append($(get_loading_img()).addClass("loading"));
		$.post("/ajax/forum_apply_conference.ajax.php",{"type":"delete_conference","conference_id":id},function(data){
			if(data)
			{
				if(data["success"])
				{
					modal.inner().find(".loading").remove();
					modal.inner().find("p").text("Conference Deleted");
					modal.inner().find("div.msgbuttons").html(make_button(global_content["ok"],"page_refresh()"));
					body_refresh();
				}
			}
		},"json");
	}
}
function recent_topic_mute(topic_id)
{
	e = $(".forum_topics[topic_id="+topic_id+"] .mute_link");
	e.html(get_loading_img()).attr("onclick","");
	$.post("/ajax/forum_mutes.ajax.php",{"type":"mute","topic_id":topic_id},function(data){
		if(data["success"])
		{
			e.html("<img src='/pics/forum_unmute.png' />").tooltip("Unmute").attr("onclick","recent_topic_unmute("+topic_id+")");
			if(hide_mutes) $(".forum_topics[topic_id="+topic_id+"]").slideUp();
		}
		else
		{
			e.html("error");
		}
	},"json");
}
function recent_topic_unmute(topic_id)
{
	e = $(".forum_topics[topic_id="+topic_id+"] .mute_link");
	e.html(get_loading_img()).attr("onclick","");
	$.post("/ajax/forum_mutes.ajax.php",{"type":"unmute","topic_id":topic_id},function(data){
		if(data["success"])
		{
			e.html("<img src='/pics/forum_mute.png' />").tooltip("Mute").attr("onclick","recent_topic_mute("+topic_id+")");
		}
		else
		{
			e.html("error");
		}
	},"json");
}
function enable_muting()
{
	$(".forum_topics").mouseover(function(){
		var e=$(this).find(".mute_link");
		if(e.length==0){
			var w = $(this).outerWidth(true);
			e=$("<div>").addClass("mute_link background_gradient align_center faux_link").appendTo(this);
			if($(this).attr("muted") == 1) e.html("<img src='/pics/forum_unmute.png' />").tooltip("Unmute").attr("onclick","recent_topic_unmute("+$(this).attr("topic_id")+")");
			else e.html("<img src='/pics/forum_mute.png' />").tooltip("Mute").attr("onclick","recent_topic_mute("+$(this).attr("topic_id")+")");
			$(this).css("position","relative");
		}
		e.show();
	})
	.mouseout(function(){$(this).find(".mute_link").hide();});
}
// *** NEW TEMPLATE STUFF ** //
function template_forum(id)
{
	id = id || "#forum";
	$(id).html(get_loading_img());
	var $forum = $("<div />");
	$forum.attr("id",$(id).attr("id"));
	if(forum_error!="")
	{
		$forum.html("");
		if(conference_id > 0 && forum_error != "conf_deleted")
		{
			$forum.append(
				template_conference_info(conference),
				$("<p/>").addClass('error').html(errors[forum_error])
				)
		}
		else $forum.append("<p class='error'>"+errors[forum_error]+"</p>"); // Add error here...
		$(id).replaceWith($forum);
		return;
	}
	if(type == "conferences")
	{
		$forum.append(
			$("<div />").append(
				jqbutton({"html":pagecontent[73],"class":"float_right","click":"pop_create_conference('"+language+"')"}),
				$("<h1/>").addClass("mega_headline topic_header").html(pagecontent[74])
				),
			template_conferences(forum_content["user_conferences"]),
			$("<div />").addClass("very_large").attr("style","margin-top: 20px; padding: 5px;").html(pagecontent[77]),
			template_conferences(forum_content["other_conferences"])
			);
	}
	else if(topic_id==0)
	{ // Show Forum Topics
		if(type == "conference") forum_content["forum"]["title"] = pagecontent[44]+" "+forum_content["conference"]["name"];
		else if(country == "int") forum_content["forum"]["title"] = style_title(type)+" "+jqcountrylink({"country":country,"get_text":true});
		else forum_content["forum"]["title"] = pagecontent[type]+" "+jqcountrylink({"country":country,"get_text":true});
		$forum.append(
			// Header
			template_forum_header(forum_content["forum"]),
			// Pagination
			template_forum_pagination(forum_content["forum"]),
			template_clear()
			);
		if(type=="conference") $forum.append(template_conference_info(conference));
				// Forum topics
		for(var i=0;i<forum_content["topics"].length;i++)
		{
			var topic = forum_content["topics"][i];
			$forum.append(
				template_topic(topic,i)
				);
		}
		$forum.append(
			template_recent_mutelink(),
			$("<div />").addClass("background_gradient").append(
				template_forum_pagination(forum_content["forum"])
			)
		);
	}
	else if(edit_id==0)
	{ // Show Topic posts
		$forum.append(
			$("<div />").addClass("background_gradient").append(
				// Pagination
				template_topic_pagination(forum_content["topic"]),
				// Lock button
				template_topic_lock(forum_content["topic"]),
				template_topic_pin(forum_content["topic"]),
				// Header
				template_topic_header(forum_content["topic"]),
				template_clear()
				)
			);
		if(forum_content["topic"]["deleted_time"] > 0)
		{
			$forum.append(
				$("<div />").addClass("topic_post background_gradient large align_center").html(pagecontent[106])
				);
		}
		else
		{
			for(var i=0;i<forum_content["posts"].length;i++)
			{
				var post = forum_content["posts"][i];
				post["i"] = i;
				$forum.append(
					template_post(post,i)
					);
			}
			$forum.append(
				$("<div />").addClass("align_left").append(
					template_topic_lock(forum_content["topic"]),//.css({"float":"left"}),
					template_topic_pin(forum_content["topic"]),//css({"float":"left"}),
					template_clear()
					)
				);
		}
	}
	else
	{
		$forum.append(
			template_post_back(forum_content["edit_post"]),
			template_clear()
//			$("<div />").addClass("backgrou
			);

	}
	$forum.append(template_forum_bottom(forum_content["topic"]));
	if(permissions["write"] && type != "recent-posts" && type != "conferences")
	{
		var write = true;
		if(forum_content["topic"])
		{
			if(forum_content["topic"]["is_locked"]==1) write = false;
		}
		if(write)
		{
			var p =	$forum.find(".topic_pages:last").length > 0?$forum.find(".topic_pages:last") : ($forum.find(".forum_pages:last").length>0 ? $forum.find(".forum_pages:last") : $forum);
			p.append(template_form());
		}
	}
	$(id).replaceWith($forum);
	get_clubs_logos();
	forum_get_ajax_content(id);
	document_ready();
}
function template_forum_bottom(topic)
{
	topic = topic || {};
	$d = $("<div />").addClass("background_gradient");
	if(topic["id"])
	{
		$d.append(
			// pages
			template_topic_pagination(topic),
			template_clear()
		);
	}
	if(user_ban) $d.append("<p class='error'>"+errors["banned"]+"</p>");
	else if(topic["is_locked"] == 1) $d.append("<p class='error'>"+errors["locked"]+"</p>");
	return $d;

}
function template_forum_pagination(forum)
{
	var postfix = "";
	if(type=="recent-posts") postfix = (admin_user>0?admin_user:user_id)+"/"+(!hide_mutes?"mutes/":"");
	var $d = $("<div />").addClass("forum_pages").append(
		$("<span />").addClass("subtle").html(pc_replace(pagecontent[59],{"[amount1]":forum["topics_from"],"[amount2]":forum["topics_to"],"[amount3]":forum["topics_count"]})+ " / "+pagecontent[63]+" "),
		template_pages(forum,postfix)
		);
	return $d;
}
function template_pages(forum,url_postfix)
{
	function get_url(pp)
	{
		if(conference_id>0)
		{
			if(topic_id > 0) return "/forum/conference/"+conference_id+"/"+topic_id+"/"+pp+"/"+url_postfix;
			return "/forum/conference/"+conference_id+"/page/"+pp+"/"+url_postfix;
		}
		if(topic_id > 0) return "/forum/"+country+"/"+type+"/"+topic_id+"/"+pp+"/"+url_postfix;
		return "/forum/"+country+"/"+type+"/page/"+pp+"/"+url_postfix;
	}
	url_postfix = url_postfix || "";
	var first_dots=false, last_dots=false;
	var pp = forum["current_page"] > 0? forum["current_page"] : 1;
	var $d = $("<span />");
	// Add prev page arrow
	if(pp>1) $d.append($("<a />").attr("href",get_url(pp-1)).addClass("page_navigation icon").html($("<img />").attr("src","/pics/cf_mini_arrow_left.png")));

	for(var i=1;i<=forum["last_page"];i++)
	{
		// Current page
		if(pp == i) $d.append($("<div />").addClass("page_navigation selected").text(i));
		// Clickable pages
		else if(i == 1 || i == forum["last_page"] || i == pp-1 || i == pp+1 || forum["last_page"] < 5)
		{
			$d.append($("<a />").attr("href",get_url(i)).addClass("page_navigation").text(i));
		}
		// between first
		else if(i<pp && !first_dots)
		{
			$d.append($("<span />").text(" ... "));
			first_dots =true;
		}
		// between last
		else if(i>pp && !last_dots)
		{
			$d.append($("<span />").text(" ... "));
			last_dots =true;
		}
	}
	// Add next page arrow
	if(pp<forum["last_page"]) $d.append($("<a />").attr("href",get_url(pp+1)).addClass("page_navigation icon").html($("<img />").attr("src","/pics/cf_mini_arrow_right.png")));
	return $d;
}
function template_forum_header(forum)
{
	var title = style_title(anti_xss(forum["title"]));
	var $d = $("<div />").addClass("float_left").append(
		$("<h1 />").addClass("mega_headline topic_header iblock").html(title)
	);
	if(permissions["write"] && type != "recent-posts") $d.append(jqbutton({"html":pagecontent[60],"click":"new_topic()"}));
	// conference buttons
	return $d;
}
function template_topic(topic)
{
	var muted = topic["muted"]?1:0;
	var $d = $("<div />").addClass("background_gradient forum_topics").attr("topic_id",topic['id']).attr("muted",muted).append(
		template_topic_likes(topic),
		template_topic_icon(topic),
		template_topic_read(topic),
		template_topic_name(topic),
		template_topic_last_post(topic),
		template_topic_last_page(topic),
		template_clear()
	);
	return $d;
}
function template_topic_likes(topic)
{
	var cl = topic["likes"]["likes"]["total"] < 0 ? "negative":"positive";
	var $d = $("<div />").addClass("topic_likes").append(
		$("<div />").addClass("likes").append(
			$("<span />").addClass(cl).tooltip(pagecontent[113]).text(Math.abs(topic["likes"]["likes"]["total"]))
		)
	);
	return $d;
}
function template_topic_icon(topic)
{
	var img = topic["moved"] > 0
		? $("<img />").attr("src","/pics/move_icon.png").attr("alt",pagecontent[114]).tooltip(pagecontent[114])
		: (topic["is_pinned"] > 0
			? $("<img />").attr("src","/pics/tack_icon.png").attr("alt",pagecontent[115]).tooltip(pagecontent[115])
			: [])
	var $d = $("<div />").addClass("topic_icon").append(img);
	return $d;
}
function template_topic_read(topic)
{
	var new_mark = topic["user_read_time"] < topic["last_reply_time"]
		? $("<img />").attr("src","/pics/eight_star_icon.png").attr("alt",pagecontent[116]).tooltip(pagecontent[116])
		: [];
	var $d = $("<div />").addClass("topic_new").append(new_mark);
	return $d;e
}
function template_topic_name(topic)
{
	var title = style_title(topic["topic_title"]);
	var tt = $("<div />").append(
		$("<strong />").addClass("large").html(title),
		$("<br />"),
		$("<strong />").html(user_names[topic["user_id"]]["club_name"]),
		$("<span />").html(get_time({"time":topic["topic_time"],"offset":tz_offset,"type":"forum"})),
		$("<br />"),
		$("<span />").html("Views: "+topic["topic_views"]),
		$("<br />"),
		$("<span />").html("Replies: "+topic["topic_replies"])
	);
	if(conference_id>0) var href="/forum/conference/"+conference_id+"/"+topic["id"]+"/1/";
	else if (type == "recent-posts") var href = "/forum/"+topic["id"]+"/";
	else var href ="/forum/"+country+"/"+type+"/"+topic["id"]+"/1/";
	var $d = $("<div />").addClass("topic_name text_fade").tooltip(tt).append(
		$("<a />").attr("href",href).addClass("large topic_link").html(title),
		template_topic_locked_icon(topic)
	);
	if(topic["is_locked"] > 0 || topic["moved"] > 0) $d.find("a.topic_link").addClass("subtle");
	else $d.find("a.topic_link").addClass("normal");

	return $d;
}
function template_topic_locked_icon(topic)
{
	var locked = topic["is_locked"] == 1
		? $("<span />").html(" ").prepend($("<img />").attr("src","/pics/padlock_icon.png").attr("alt",pagecontent[103]).tooltip(pagecontent[103])).prepend(" ")
		: [];
	return locked;
}
function template_topic_last_post(topic)
{
	var $d = $("<div />").addClass("topic_last_post subtle small");
	if(topic["last_reply_time"] > topic["topic_time"])
	{
		var topic_replier = user_names[topic["topic_replier"]] ? user_names[topic["topic_replier"]]["club_name"] : "";
		$d.append(
			$("<div />").html(topic_replier),
			$("<div />").html(get_time({"time":topic["last_reply_time"],"offset":tz_offset,"type":"forum"}))
			);
	}
	return $d;
}
function template_topic_last_page(topic)
{
	var href ="/forum/"+country+"/"+type+"/"+topic["id"]+"/last/#last";
	var $d = $("<div />").addClass("topic_last_page").append(
		$("<a />").attr("href",href).addClass("page_navigation").text(topic["last_page"])
		);
	return $d;
}
function template_recent_mutelink()
{
	var pp = page > 1 || page == "last" ? page : 1;
	var user = admin_user > 0 ? admin_user : user_id;
	if(type != "recent-posts") return [];
	if(hide_mutes) var href="/forum/int/recent-posts/page/"+pp+"/"+user+"/mutes/";
	else var href="/forum/int/recent-posts/page/"+pp+"/"+user+"/";
	return $("<div />").addClass("align_right").html($("<a />").attr("href",href).addClass("subtle unbold").html("Toggle Mutes"));
}
// ** For show topic posts ** //
function template_topic_pagination(topic)
{
	var $d = $("<div />").addClass("topic_pages").append(
		template_topic_back(),
		$("<span />").addClass("subtle").html(pagecontent[100]+" "+topic["posts_from"]+"-"+topic["posts_to"]+" "+pagecontent[101]+" "+topic["topic_replies"]+" / "+pagecontent[102]+" "),
		template_pages(topic,"")
		);
	return $d;
}
function template_topic_back()
{
	if(conference_id>0) var href="/forum/conference/"+conference_id+"/";
	else href="/forum/"+country+"/"+type+"/";
	var $d = $("<div />").addClass("back_button align_left").html($("<a />").attr("href",href).addClass("arrow_left").html(global_content["back"]));
	return $d;
}
function template_post_back(post)
{
	if(conference_id>0) var href="/forum/conference/"+conference_id+"/"+post["topic_id"]+"/"+page+"/";
	else href="/forum/"+country+"/"+type+"/"+post["topic_id"]+"/"+page+"/";
	var $d = $("<div />").addClass("back_button align_left").html($("<a />").attr("href",href).addClass("arrow_left").html(global_content["back"]));
	return $d;
}
function template_topic_lock(topic)
{
	if(!permissions["admin"]) return [];
	if(topic["is_locked"]==1)
	{
		var text = pagecontent[104];
		var $d = jqbutton({"html":$("<span/>").append($("<img />").attr("src","/pics/padlock_icon.png").tooltip(text)," ",$("<span />").addClass("subtle").html(text)),"class":"lock_button","click":"unlock_topic("+topic["id"]+")"});
	}
	else
	{
		var text = pagecontent[105];
		var $d = jqbutton({"html":$("<span/>").append($("<img />").attr("src","/pics/padlock_icon.png").tooltip(text)," ",$("<span />").addClass("subtle").html(text)),"class":"lock_button","click":"lock_topic("+topic["id"]+")"});
	}
	return $d;
}
function template_topic_pin(topic)
{
	if(!permissions["admin"]) return [];
	if(topic["is_pinned"]==1)
	{
		var text = "Unpin";
		var $d = jqbutton({"html":$("<span/>").append($("<img />").attr("src","/pics/tack_icon.png").tooltip(text)," ",$("<span />").addClass("subtle").html(text)),"class":"lock_button","click":"unpin_topic("+topic["id"]+")"});
	}
	else
	{
		var text = "Pin";
		var $d = jqbutton({"html":$("<span/>").append($("<img />").attr("src","/pics/tack_icon_subtle.png").tooltip(text)," ",$("<span />").addClass("subtle").html(text)),"class":"lock_button","click":"pin_topic("+topic["id"]+")"});
	}
	return $d;
}
function template_topic_header(topic)
{
	var $d = $("<div />").append(
		$("<h1/>").addClass("mega_headline topic_header").html(style_title(anti_xss(topic["topic_title"])))
		);
	return $d;
}
function template_post(post,index)
{
	var $d = $("<div />").addClass("topic_post background_gradient").attr("id","post"+post["post_id"]).attr("i",index+"").append(
		template_post_user(post),
		template_post_content(post),
		template_post_right(post),
		template_clear()
	);
	return $d;
}
function template_post_user(post)
{
	var pro = user_names[post["user_id"]]["is_pro"];
	var diamond = user_names[post["user_id"]]["is_diamond"];
	var $d = $("<div />").addClass("user dark").append(
		template_post_user_logo(post),
		template_post_user_name(post),
		template_post_user_icons(post),
		template_post_user_rank(post),
		template_post_user_teamster(post),
		template_post_user_clubs(post)
	);
	if(diamond) $d.addClass("diamond");

	return $d;
}
function template_post_user_logo(post)
{
	if(!user_names[post["user_id"]]["is_pro"] && !user_names[post["user_id"]]["is_diamond"]) return [];
	clubs_wo_logo[clubs_wo_logo.length] = post["user_id"];
	var size = user_names[post["user_id"]]["big_forum_logo"] || user_names[post["user_id"]]["is_diamond"] ? "large":"normal";
	var $d = $("<a />").attr("href","/club/"+post["user_id"]+"/").attr("no_logo",post["user_id"]).attr("logo_size",size).addClass("logo_"+size);
	return $d;
}
function template_post_user_name(post)
{
	var $d = $("<div />").append(
			jqclublink({"name":user_names[post["user_id"]]["club_name"],"id":post["user_id"],"class":"normal","auto_tooltip":true})
		);
	return $d;
}
function template_post_user_icons(post)
{
	var $d = $("<div />").addClass("valign_all").append(
			jqcountrylink({"country":user_names[post["user_id"]]["country"]}),
				$("<span />").html(
				" "+(user_names[post["user_id"]]["pro_icon"]||"")+
				" "+(user_names[post["user_id"]]["vet_icon"]||"")+
				" "+user_names[post["user_id"]]["online_icon"])
			);

	return $d;
}
function template_post_user_rank(post)
{
	var $d = $("<span />").addClass("user_rank italic").html(user_names[post["user_id"]]["rank"]["rank"]+ "("+user_names[post["user_id"]]["rank"]["likes"]+")").tooltip(pagecontent[127]);
	return $d;
}
function template_post_user_teamster(post)
{
	var teamster = false;
	var t = user_names[post["user_id"]]["teamster"];
	var $d = $("<div />");
	for(var i in t)
	{
		if(t[i])
		{
			$d.append($("<img/>").addClass('forum_rank').attr("src",'/pics/icons/forum_micro_'+i+'.png'));
			teamster = true;
		}
	}
	if(teamster) return $d;
	return [];
}
function template_post_user_clubs(post)
{
	var clubs = user_names[post["user_id"]]["clubs"];
	if(clubs.length <= 1) return [];
	var $ul = $("<ul />").addClass("zebra");
	for(var i in clubs)
	{
		if(i == post["user_id"]) continue;
		var c = clubs[i];
		if(user_names[post["user_id"]]["is_pro"] || user_names[post["user_id"]]["is_diamond"]) clubs_wo_logo[clubs_wo_logo.length] = c["id"];
		$ul.append(
			$("<li />").css({"position":"relative"}).append(
				$("<div />").attr("style","position:absolute; right: 2px; height: 25px;").html(jqcountrylink({"country":c["country"]})),
				$("<div />").addClass("small_logo_box float_left").attr("style","width: 25px; height: 25px; margin-right: 3px; display: inline-block").attr("no_logo",c["id"]).attr("logo_size","small"),
				jqclublink({"name":c["club_name"],"id":c["id"],"class":"normal","attr":{"style":"vertical-align:top;color:#B8D988"},"auto_tooltip":true}),
				template_clear()
				)
			);
	}
	var $d = $("<div />").addClass("small subtle align_left nowrap multi_clubs").css({"line-height":"25px"}).append(
		$ul
		);
	ul_zebra($ul);

	return $d;
}
function template_post_content(post)
{
	var del = post.deleted_time == "0" ? "" : "<div class='bold text_red'>DELETED</div>";
	var $d = $("<div />").addClass("content").append(
		del,
		$("<div />").addClass("text").append(
			template_post_content_text(post),
			template_post_content_edit(post),
			template_post_content_signature(post)
		)
	);
	return $d;
}
function template_post_content_text(post)
{
	var styles = user_names[post["user_id"]]["all_styles"];

	var $d = $("<span />").append(forum_style_text(post["post_text"],{"hide_styles":!styles,"type":"forum","ajax_content":content_to_ajax}));
	if(post["post_text_translated_from"])
	{
		$d.append(
			$("<div />").addClass("align_center").html("<br /><span class='large italic bold text_pink'>====== Translated From ======</span>"),
			$("<div />").addClass("bold large").html(forum_content["topic"]["topic_title_translated_from"]),
			$("<div />").html(forum_style_text(post["post_text_translated_from"]))
		);
	}
	return $d;
}

function template_post_content_edit(post)
{
	var $d = $("<div />");
	if(post["post_edit_time"] > 0)
	{
		$d.append(
			$("<div />").addClass("subtle italic small align_right").html(pc_replace(pagecontent[40],{"[amount]":post["post_edit_count"],"[date]":get_time({"time":post["post_edit_time"],"offset":tz_offset,"type":"forum"})}))
		);
	}
	return $d;
}

function template_post_content_signature(post)
{
	if(!user_names[post["user_id"]]["is_pro"] && !user_names[post["user_id"]]["is_diamond"]) return [];
	var $d = $("<div />").addClass("signature clearfix").html(
		anti_xss(user_names[post["user_id"]]["signature"]).replace(/\n/ig,"<br />")
	);
	return $d;
}

function template_post_right(post)
{
	var $d = $("<div />").addClass("actions").append(
		template_post_right_num(post),
		template_post_right_time(post),
		template_post_right_likes(post), // Not when conference
		template_post_right_buttons(post)
	);
	return $d;
}

function template_post_right_num(post)
{
	var $d = $("<div />").addClass("post_number").append(
		$("<a />").attr("href","#"+post["post_number"]).attr("id","p"+post["post_number"]).text("#"+post["post_number"])
	);
//	if(post["i"]+1 == forum_content["posts"].length) $d.prepend("<a id='last' name='last'></a>");
	return $d;
}

function template_post_right_time(post)
{
	var $d = $("<div />").addClass("post_time").tooltip(get_time({"time":post["post_time"],"offset":tz_offset,"style":"long"}),"text").html(get_time({"time":post["post_time"],"offset":tz_offset,"type":"forum"}));

	return $d;
}

function template_post_right_likes(post)
{
	var $d = $("<div />").addClass("likes").attr("id","like_post"+post["post_id"]).attr("onclick","pop_likes("+post["post_id"]+")").tooltip("get_likes("+post["post_id"]+")").append(
		$("<span />").addClass("positive").attr("current_value",Number(post["likes"]["likes"][1])).html(Math.abs(post["likes"]["likes"][1])),
		$("<span />").addClass("negative").attr("current_value",Number(post["likes"]["likes"][2])).html(Math.abs(post["likes"]["likes"][2]))
	);
	if(post["likes"]["likes"][1] <= 0) $d.find(".positive").hide();
	if(post["likes"]["likes"][2] <= 0) $d.find(".negative").hide();

	return $d;
}

function template_post_right_buttons(post)
{
	var $d = $("<div />").addClass("hidden_buttons_wrap").append(
		$("<div />").addClass("hidden_buttons").append(
			template_post_right_buttons_like(post),
			template_post_right_buttons_reply(post),
			template_post_right_buttons_translate(post)
		)
	);

	return $d;
}

function template_post_right_buttons_like(post)
{
	if(post["user_id"] == user_id) return []; //Cant like own posts
	if(post["likes"]["user"] > 0) return []; // Can't like twice
	if(conference_id > 0) return [];
	var $d = $("<div />").addClass("like_buttons").attr("id","like_buttons"+post["post_id"]).append(
		jqbutton({"html":'<img class="like_icon" src="/pics/thumb_up.png"/>',"click":"like_post("+post["post_id"]+",1)"}),
		jqbutton({"html":'<img class="like_icon" src="/pics/thumb_down.png"/>',"click":"like_post("+post["post_id"]+",2)"})
	);
	return $d;
}

function template_post_right_buttons_reply(post)
{
	var $d = $("<div />").addClass("reply_buttons").append(
		$("<span />").attr("id","quote_post"+post["post_number"]).append(
			$("<span />").addClass("quote_name").html(user_names[post["user_id"]]["club_name"]),
			$("<span />").addClass("quote_text").html(post["quote_text"])
		).hide()
	);
	if(forum_content["topic"]["is_locked"] == 0)
	{
		$d.append(
			jqbutton({"html":pagecontent[41],"click":"reply()"}),
			jqbutton({"html":"<img src='/pics/forum/mega_quotes.png' style='width:10px' /> "+pagecontent[42],"click":"quote("+post["post_number"]+")"})
			);
	}
	if(post["user_id"] == user_id || permissions["admin"])
	{ // Edit button
		$d.append(jqbutton({"html":"<img src='/pics/icons/pen.gif' /> "+pagecontent[107],"href":"/forum/"+country+"/"+type+"/"+forum_content["topic"]["id"]+"/"+(page=="last"?forum_content["topic"]["last_page"] : page)+"/edit/"+post["post_id"]+"/","class":"edit_button"}))
	}
	if(permissions["admin"])
	{
		$d.append(jqbutton({"html":"<img src='/pics/small_red_x.png' /> "+pagecontent[109],"click":"pop_delete_post("+post["post_id"]+")","class":"edit_button"}))
	}
	if(permissions["ban"])
	{
		$d.append(jqbutton({"html":"<img src='/pics/forum/banuser.gif' /> "+pagecontent[110],"click":"pop_forum_ban("+post["user_id"]+","+post["post_id"]+")","class":"edit_button"}))
	}
	if(permissions["user_agent"])
	{
		if(post["user_agent"] != "")
		{
			$d.append($("<div />").addClass("subtle small clearfix").click(function(){ modal.html(post["user_agent"]).show()}).tooltip(post["user_agent"]).html("<hr /><span>"+pagecontent[111]+"</span>"));
		}
	}
	return $d;
}
function template_post_right_buttons_translate(post)
{
	if(permissions["admin_translate"] && post["is_topic_head"] == 1)
	{
		return $("<div />").addClass("reply_buttons").append(jqbutton({"href":"/admin_new/translate_announcements/?announcement="+post["topic_id"],"html":"Translate"}));
	}
	return [];
}
function template_post_(post)
{
	var $d = $("<div />");

	return $d;
}

function template_form()
{
	var edit = forum_content["edit_post"];
	var options = is_pro||is_diamond||permissions["admin"] ? template_form_options() : [];
	var head = $("<div />").addClass("forum_center very_large align_left").html(pagecontent[41]);
	if((topic_id==0 && (forum_id>0 || conference_id>0)) || edit) // or edit post
	{
		var text = forum_content["post"] ? forum_content["post"]["topic_title"] : anti_xss($POST["topic_title"]);
		if(edit) text = edit["topic_title"];
		head = $("<div />").addClass("align_left large forum_center").append(
			$("<div />").addClass("large").html(pagecontent[60]),
			$("<div />").addClass("align_center").append(
				$("<input />").attr("type","text").attr("id","topic_title").attr("name","topic_title").addClass("embossed forum_center").attr("tabindex",1).val(text)
				)
			);
		if(edit) if(edit["is_topic_head"]==0) head = [];
	}
	var text = forum_content["edit_post"] ? forum_content["edit_post"]["post_text"] : anti_xss($POST["topic_content"]);
	var $d = $("<div />").addClass("forum_form").append(
		$("<div />").addClass("error").html(post_error).hide(),
		$("<form />").attr("id","forum_post_form").attr("method","post").attr("action","").attr("id","forum_post_form").append(
			head,
			options,
//			$("<input />").attr("type","hidden").attr("name","forum_id").val(forum_id),
//			$("<input />").attr("type","hidden").attr("name","forum_country").val(country),
//			$("<input />").attr("type","hidden").attr("name","forum_type").val(type),
//			$("<input />").attr("type","hidden").attr("name","topic_id").val(topic_id),
			$("<div />").addClass("align_center").append(
				$("<textarea />").attr("name","topic_content").attr("id","topic_content").addClass("embossed forum_center").attr("rows","10").attr("tabindex",2).html(text),
				template_form_edit(edit),
				$("<div />").addClass("textarea_buttons").attr("id","textarea_buttons").append(
					jqbutton({"html":"<input type='submit' name='submit_post' id='topic_content_submit' value='"+pagecontent[93]+"' class='submit' tabindex='3'/>"}),
					jqbutton({"html":pagecontent[94],"click":"pop_preview2()","tabindex":4})
				)
			)
		)
	);
	if(post_error!="") $d.find(".error").show();
	return $d;
}
function template_form_edit(edit)
{
	var $d = $("<div />");
	if(!edit) return [];
	if(permissions["admin"] && edit["is_topic_head"] == 1)
	{ // Append pin/lock/move
		var $move = $("<select />").attr("id","move_to_forum").attr("name","move_to_forum");
		if(edit["moved_to_forum_id"] > 0) $move.append($("<option />").val(edit["moved_to_forum_id"]).html(pagecontent[126]));
		else $move.append($("<option />").val(edit["forum_id"]).html(pagecontent[126]));
		for(var i=0;i<forums.length;i++)
		{
			var f = forums[i];
			if((permissions["admin_country"] == "all" || permissions["admin_country"] == f["country"]) && f["type"]!="league-press")
			{
				var $o = $("<option />").val(f["id"]).html("["+f["country"]+"] "+f["type"]).appendTo($move);
			}
		}
		$d.append(
			$("<label />").attr("for","move_to_forum").html(" "+pagecontent[92]),
			$move,
			" ",
			$("<input />").attr("type","checkbox").attr("name","topic_shadow").attr("id","topic_shadow").val(1).attr("checked",(edit["moved_to_forum_id"]>0)),
			$("<label />").attr("for","topic_shadow").html("Shadow")
		)
	}
	return $d;
}
function template_form_options()
{
	var $d = $("<div />").addClass("textarea_icons").append(
		jqbutton({"html":"<img src='/pics/bold_b.png' />","tooltip":pagecontent[118],"click":"add_bbcode('bold')"}),
		jqbutton({"html":"<img src='/pics/italic_i.png' />","tooltip":pagecontent[119],"click":"add_bbcode('italic')"}),
		jqbutton({"html":"<img src='/pics/html_icon.png' />","tooltip":pagecontent[120],"click":"add_bbcode('pre')"}),
		jqbutton({"html":"<img src='/pics/color_dots.png' />","tooltip":pagecontent[121],"click":"toggle_color_picker()","id":"color_picker_button"}),
		jqbutton({"html":pagecontent[87],"tooltip":pagecontent[122],"click":"prompt_value('link')"}),
		jqbutton({"html":pagecontent[88],"tooltip":pagecontent[123],"click":"prompt_value('image')"}),
		jqbutton({"html":"<img src='/pics/player_icon.gif' />","tooltip":pagecontent[124],"click":"prompt_value('player')"}),
		jqbutton({"html":"<span class='smiley smiley3'></span>","tooltip":pagecontent[125],"click":"toggle_smiley_picker()","id":"smiley_picker_button"}),
		$("<div />").attr("id","smiley_picker").append(
			$("<div />").addClass("border").append(
				$("<span />").addClass("smiley smiley1").attr("onclick","add_bbcode('smiley',1)"),
				$("<span />").addClass("smiley smiley2").attr("onclick","add_bbcode('smiley',2)"),
				$("<span />").addClass("smiley smiley3").attr("onclick","add_bbcode('smiley',3)"),
				$("<span />").addClass("smiley smiley4").attr("onclick","add_bbcode('smiley',4)"),
				$("<span />").addClass("smiley smiley5").attr("onclick","add_bbcode('smiley',5)"),
				$("<span />").addClass("smiley smiley6").attr("onclick","add_bbcode('smiley',6)"),
				$("<span />").addClass("smiley smiley7").attr("onclick","add_bbcode('smiley',7)")
			)
		),
		$("<div />").attr("id","color_picker").append(
			$("<div />").addClass("border").append(
				$("<span />").addClass("color yellow").attr("onclick","add_bbcode('color', 'yellow')"),
				$("<span />").addClass("color orange").attr("onclick","add_bbcode('color', 'orange')"),
				$("<span />").addClass("color red").attr("onclick","add_bbcode('color', 'red')"),
				$("<span />").addClass("color purple").attr("onclick","add_bbcode('color', 'purple')"),
				$("<span />").addClass("color blue").attr("onclick","add_bbcode('color', 'blue')"),
				$("<span />").addClass("color pink").attr("onclick","add_bbcode('color', 'pink')"),
				$("<span />").addClass("color black").attr("onclick","add_bbcode('color', 'black')")
			)
		)
	);
	return $d;
}
function template_conferences(conferences)
{
	var $d = $("<div />");
	for(var i=0;i<conferences.length;i++)
	{
		var c = conferences[i];
		$("<div />").addClass("background_gradient conference").tooltip(pagecontent[75]+"<br />"+forum_style_text(c["description"])).append(
			$("<div />").addClass("icon").html(c["is_private"] == 1 ? $("<img />").attr("src","/pics/padlock_icon.png") : ""),
			$("<div />").addClass("name").html($("<a />").attr("href","/forum/conference/"+c["conference_id"]+"/").addClass("large normal conference_link").html(anti_xss(c["name"]))),
			$("<div />").addClass("topics subtle").html(c["topic_count"]),
			$("<div />").addClass("language subtle").html(languages[c["language"]])
		).appendTo($d);
	}
	return $d;
}
function template_conference_info(conf)
{
	var $d = $("<div />").attr("id","conference").addClass("std").append(
		$("<div/>").append($("<span />").addClass("bold").html(pagecontent[44]),$("<span />").html(anti_xss(conf["name"]))),
		$("<div/>").append($("<span />").addClass("bold").html(pagecontent[45]),$("<span />").html(jqclublink({"id":conf["owner"],"flag":true,"auto_tooltip":true}))),
		$("<div/>").append($("<span />").addClass("bold").html(pagecontent[46]),$("<span />").html(languages[conf["language"]])),
		$("<div/>").append($("<span />").addClass("bold").html(pagecontent[47]),$("<span />").html(forum_style_text(conf["description"])))
	);
	content_to_ajax["clubs"].push(conf["owner"]);
	if(!conference_user && conf["is_private"] == 1)
	{
		$d.append(
			jqbutton({"html":pagecontent[55],"click":"forum_apply_membership("+conf["id"]+")"})
		);
	}
	else
	{
		if(!conference_user) $d.append(jqbutton({"html":pagecontent[56],"click":"join_conference("+conf["id"]+")"}));
		$d.append(jqbutton({"html":pagecontent[57],"click":"pop_conference_members("+conf["id"]+")"}));
	}
	if(conference_user)
	{
		$d.append(jqbutton({"html":pagecontent[51],"click":"pop_conference_invite("+conference_id+")"})); // invite
		if(conference_user["member_type"] < 2)
		{ // Not owner
			$d.append(jqbutton({"html":pagecontent[52],"click":"leave_conference("+conference_id+")"})); // leave
		}
		if(conference_user["member_type"] > 0)
		{// admin
			$d.append(
				jqbutton({"html":pagecontent[49],"click":"pop_conference_applications("+conference_id+")"}), // show appl
				jqbutton({"html":pagecontent[50],"click":"pop_edit_conference("+conference_id+")"}) // edit
			);
		}
		if(conference_user["member_type"] == 2)
		{//owner
			$d.append(jqbutton({"html":global_content["delete"],"click":"delete_conference("+conference_id+")"})); // delete
		}
	}
	$d = $("<div />").append(
		$d.hide(),
		jqbutton({"html":pagecontent[61],"click":function(){ $("#conference").slideToggle()}})
	);
	if(conf["invite"] && !conference_user)
	{
		$d.append($("<div />").addClass("pro_offer").append(
			$("<span />").html(pagecontent[58]+" "),
			jqbutton({"html":pagecontent[56],"click":"join_conference("+conf["id"]+")"})
			)
		);
	}
	return $d;
}
function template_clear()
{
	return $("<div />").addClass("clear");
}
function style_title(str)
{
	var s = str.split(" ");
	for(var i=0;i<s.length;i++)
	{
		var ss = s[i].split(/[\[\]\(\)_#@\.\/=?!+-]/);
		for(var j=0;j<ss.length;j++)
		{
			if(ss[j] != "")
			{
				if(ss[j] != "TM" && ss[j] != "NT")
				{
					if(ss[j].substr(0,1) == ss[j].substr(0,1).toUpperCase() || i==0)
					{
						str = str.replace(ss[j],ucfirst(ss[j]));
					}
				}
			}
		}
	}
	return str;
}
function ucfirst(str)
{
	str = str || "";
	return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
}
function anti_xss(str)
{
	str = str || "";
	str.replace(/[<>]/gi,"");
	return str;
}
function get_clubs_logos()
{
	clubs_wo_logo.push(user_id);
	$.post("/ajax/forum_get.ajax.php",{"type":"get_logos","clubs":clubs_wo_logo},function(data){
		for(var i in data["clubs"])
		{
			var md5 = data["clubs"][i];
			if(md5 == "default")
			{
				$("[no_logo="+i+"]").each(function(){
					$(this).append(jqclublogo({"id":i,"size":$(this).attr("logo_size"),"md5":md5,"default":true}))
					});
				if(i==user_id) user_logo = jqclublogo({"id":i,"size":"normal","md5":md5,"default":true})
			}
			else
			{
				$("[no_logo="+i+"]").each(function(){
					$(this).append(jqclublogo({"id":i,"size":$(this).attr("logo_size"),"md5":md5}))
					});
				if(i==user_id) user_logo = jqclublogo({"id":i,"size":"normal","md5":md5});
			}
		}
	},"json");
}
function document_ready()
{
	var offset;
	if(location.hash=="#last") offset = $(".topic_post:last").offset();
	else if(location.hash.substr(1)>0) offset = $("#p"+location.hash.substr(1)).closest(".topic_post").offset();
	if(offset)
	{
		setTimeout(function(){
			$(window).scrollTop(offset.top-10);
		},300);
	}

	$(".topic_post").mouseover(function(){
		var $hide = $(this).find(".hidden_buttons");
		$hide.parent().css({"position":"absolute","width":"100px"}).show();
//		$(this).find(".edit_button").show();
	}).mouseout(function(){
		$(this).find(".hidden_buttons_wrap").hide();
//		$(this).find(".edit_button").hide();
	});
	$("#topic_content").keyup(function(e){
		update_textarea_height("topic_content");
		if(e.ctrlKey && SESSION["is_pro"])
		{ //
			if(e.keyCode == 66) // key: b
			{
				add_bbcode('bold');
				return false;
			}
			else if(e.keyCode == 73) // key: i
			{
				add_bbcode('italic');
				return false;
			}
		}
	});
	$(".forum_topics")
		.mouseover(function(){
			$(this).addClass("hover");
		})
		.mouseout(function(){
			$(this).removeClass("hover");
		});
		$(".forum_topics").find(".topic_likes, .topic_icon, .topic_new, .topic_name, .topic_last_post") // All But Last Post
		.click(function(e){
			var href = $(this).closest(".forum_topics").find(".topic_link").attr("href");
			// ARGH!
			if(e.ctrlKey || e.which == 2)
			{ // CTRL held or middle mouseclick
				window.open(href);
			}
			else
			{
				window.location = href;
			}
			return false;
		})
		.keypress(function(e){
			if(e.keyCode == 13)
			{
				$(this).click();
			}
		});
	$(".conference")
		.mouseover(function(){
			$(this).addClass("hover");
		})
		.mouseout(function(){
			$(this).removeClass("hover");
		})
		.click(function(e){
			// ARGH!
			if(e.ctrlKey)
			{
				window.open($(this).find(".conference_link").attr("href"));
			}
			else
			{
				window.location = $(this).find(".conference_link").attr("href");
			}
			return false;
		})
		.keypress(function(){
			$(this).click();
		});
	// place color picker..
	if($("#color_picker_button").length > 0)
	{
		setTimeout(function(){
			$("#color_picker").css({
				"position":"absolute",
				"left":$("#color_picker_button").position().left+"px",
				"top":(parseInt($("#color_picker_button").position().top)+parseInt($("#color_picker_button").height()))+"px"
			});
			$("#smiley_picker").css({
				"position":"absolute",
				"left":$("#smiley_picker_button").position().left+"px",
				"top":(parseInt($("#smiley_picker_button").position().top)+parseInt($("#smiley_picker_button").height()))+"px"
			});
		},1000);
	}
	setTimeout(function(){
		$(".text_fade").each(function(){make_text_fade($(this),"forum")});
	},100);
//	make_checkbox("topic_pinned");
//	make_checkbox("topic_locked");
	make_checkbox("topic_shadow");
	$("#move_to_forum").selectmenu({
		"style":"dropdown",
		"maxHeight":"400",
		"menuWidth":"200",
		"width": "160",
		format: flag_format
	});
	activate_club_links($("#forum [club_link]"));
	activate_player_links($("#forum [player_link]"));
	if(type=="recent-posts") enable_muting();
}
// optimized jquery button
function jqbutton(ar)
{
	ar = ar || {};
	if(ar["href"])
	{
		var bb = $("<a />").addClass("button").html(
			$("<span />").addClass("button_border").append(ar["html"] || "")
			).attr("href",ar["href"]);
	}
	else
	{
		var bb = $("<span />").addClass("button").html(
			$("<span />").addClass("button_border").append(ar["html"] || "")
			);
	}
	if(ar["style"]) bb.attr("style",ar["style"]);
	if(ar["class"]) bb.addClass(ar["class"]);
	if(ar["id"]) bb.attr("id",ar["id"]);
	// click action
	if(ar["click"])
	{
		if(typeof ar["click"] == "function")
		{
			bb.click(function(){ar["click"].call(this)})
			.keypress(function(e){
				if(e.keyCode != 13 && e.keyCode != 32) return false; // only return/enter+space
			});
		}
		else bb.attr("onclick",ar["click"]).attr("onkeypress",ar["click"]);

	}
	// tabindex
	if(ar["tabindex"]) bb.attr("tabindex",ar["tabindex"]);
	else bb.attr("tabindex",tabindex++);
	if(ar["focus"]) bb.attr("focus",ar["focus"]);
	// return string not jq elem
	if(ar["string"]) bb = $("<div />").html(bb).html();
	return bb;
}
function pop_preview2()
{
	var data = {};
	data["flag"] = get_flag(SESSION["country"]);
	data["pro"] = pro_icon;
	var text = $("#topic_content").val();
	data["text"] = forum_style_text(text,{"hide_styles":!user_styles});
	data["time"] = "??:??";
	data["logo"] = $("<div />").html(user_logo).html();
	data["name"] = SESSION["clubname"];
	var $div = $("<div />").addClass("post_preview");
	if($("#topic_title").val() != "")
	{
		$("<h1>").addClass("mega_headline topic_header").appendTo($div).html($("#topic_title").val());
	}
	var $post = $("<div />").addClass("topic_post background_gradient");
	var $user = $("<div />").addClass("user dark").appendTo($post).append(data["logo"]+"<div>"+data["name"]+"</div>"+"<div>"+data["flag"]+" "+data["pro"]+"</div><em>"+pagecontent[139]+"</em>");
	var $text = $("<div />").addClass("text").html(data["text"]).wrap("<div class=\"content\" />").parent().appendTo($post);
	modal.outer().css({
		"width":"806px"
	});
	var $actions = $("<div />").addClass("actions").append('<div class="post_number">#?</div><div class="post_time">'+data["time"]+'</div><div class="">Likes: 0</div>').appendTo($post);
	$post.append("<div class=\"clear\" />");
	var $buttons = $("<div />").addClass("textarea_buttons background_gradient");
	$buttons.append(
		jqbutton({"html":pagecontent[93],"click":"submit_forum_post()","class":"forum_submit_button","focus":"-"}),
		jqbutton({"html":global_content["cancel"],"click":"modal.hide()"})
		)
	// Append
	$div.append($post).append($buttons);
	modal.outer().addClass("no_background");
	modal.html($div).show();
	modal.reposition();
}
function forum_get_ajax_content(elem)
{
	if(content_to_ajax["clubs"].length==0 && content_to_ajax["players"].length == 0) return false;
	$.post("/ajax/feed_get.ajax.php",{"type":"club_names","ids":content_to_ajax["clubs"],"player_ids":content_to_ajax["players"]},function(data){
		if(data != null)
		{
			for(var i=0;i<data["clubs"].length;i++)
			{
				var c = data["clubs"][i];
				$(elem).find("[club_link="+c["id"]+"]").text(c["name"]);
			}
			content_to_ajax["clubs"] = [];
			for(var i=0;i<data["players"].length;i++)
			{
				var c = data["players"][i];

				$(elem).find("[player_link="+c["id"]+"]").each(function(){
					var $span = $("<span/>").addClass("player_name nowrap").insertBefore($(this)).append(
						$("<span/>").html(rec_format(c["rec"])),
						" ",
						$(this).text(c["name"]).attr("player_link","")
						);
					if(c["expiry"])
					{ // transferlisted
						var exp = "Expiry: "+c["expiry"]+"<br />";
						if(c["currentbid"] > 0) exp += "Current bid: "+money(c["currentbid"]);
						else exp += "Minimum bid: "+money(c["min_price"]);
						$span.append(" ",$("<img src='/pics/auction_hammer_small.png'/>").tooltip(exp));
					}
				});
			}
			content_to_ajax["players"] = [];
		}
	},"json");
}
// Js version of php function - takes ofset to calculate the user local time
function get_time(ar)
{
	if(ar["style"]) return timestamps[ar["time"]][ar["style"]];
	return timestamps[ar["time"]]["short"];
	ar["offset"] = ar["offset"] || 0;
	var date = new Date((parseInt(ar["time"])+parseInt(ar["offset"]))*1000);
	var h = zeros(date.getHours());
	var i = zeros(date.getMinutes());
	var s = zeros(date.getSeconds());
	var y = date.getFullYear();
	var m = date.getMonth()+1;
	var d = date.getDate();
	var ddate = y+zeros(m)+zeros(d);
	var months = get_time_months();

	// Now for comparison
	var now = new Date((Math.floor((new Date).getTime()/1000)+ar["offset"])*1000);
	var nowy = now.getFullYear();
	var nowm = now.getMonth()+1;
	var nowd = now.getDate();
	var nowdate = nowy+zeros(nowm)+zeros(nowd);
	if(ar["type"] == "forum")
	{
		if(nowdate == ddate) return h+":"+i;
		return d+". "+months[m]["short"];
	}
	return y+"-"+zeros(m)+"-"+zeros(d)+" "+h+":"+i+":"+s;
}
function get_time_months()
{
	var months = {
		1:{"short":global_content["jan_month"],"long":global_content["january"]},
		2:{"short":global_content["feb_month"],"long":global_content["february"]},
		3:{"short":global_content["mar_month"],"long":global_content["march"]},
		4:{"short":global_content["apr_month"],"long":global_content["april"]},
		5:{"short":global_content["may_month"],"long":global_content["may"]},
		6:{"short":global_content["jun_month"],"long":global_content["june"]},
		7:{"short":global_content["jul_month"],"long":global_content["july"]},
		8:{"short":global_content["aug_month"],"long":global_content["august"]},
		9:{"short":global_content["sep_month"],"long":global_content["september"]},
		10:{"short":global_content["oct_month"],"long":global_content["october"]},
		11:{"short":global_content["nov_month"],"long":global_content["november"]},
		12:{"short":global_content["dec_month"],"long":global_content["december"]}
	}
	return months;
}
function zeros(str,digits)
{
	str+="";
	digits = digits || 2;
	while(str.length < digits)
	{
		str = "0"+str;
	}
	return str;
}
// Style text (clubnames + other styling)
function forum_style_text(text,settings)
{
	settings = settings || {};
	text = text || "";
	while(/\n\n\n/g.test(text))
	{
		text = text.replace(/\n\n\n/g,"\n\n");
	}
	text = text
		// tags
		.replace(/</g,"&lt;")
		.replace(/>/g,"&gt;")
		// clear whitespace from list
		.replace(/[\s\n\r]*\[li\]([\s\S]+?)\[\/li\][\s\n\r]*/g,"[li]$1[/li]")
		// breaks
		.replace(/\n/g,"\n<br />")
		.replace(/\r/g,"")
		.replace(/\[br\]/g,"\n<br />")
		// Punctuation spammers
		.replace(/!+/g,"!")
		.replace(/\?+/g,"?")
		.replace(/[\?!][\?!]+/g,"?")
		.replace(/\[bracketl\]/g,"&#91;")
		.replace(/\[bracketr\]/g,"&#93;")
	function escape_regexp_str(t) {
    	return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
	}
	if(!settings["hide_styles"])
	{
		text = text
			//text style
			.replace(/\[b\]([\s\S]+?)\[\/b\]/g,"<strong>$1</strong>")
			.replace(/\[i\]([\s\S]+?)\[\/i\]/g,"<em>$1</em>")
			.replace(/\[pre\]([\s\S]+?)\[\/pre\]/g,function(str,pre){
				return "<pre>"+pre.replace(/\n\<br \/\>/g,"\n")+"</pre>";
			})
			.replace(/\[strike\]([\s\S]+?)\[\/strike\]/g,"<span class='strike'>$1</span>")
			.replace(/\[subtle\]([\s\S]+?)\[\/subtle\]/g,"<span class='subtle'>$1</span>")
			// colors
			.replace(/\[color=yellow\]([\s\S]+?)\[\/color\]/g,"<span class='text_yellow'>$1</span>")
			.replace(/\[color=orange\]([\s\S]+?)\[\/color\]/g,"<span class='text_orange'>$1</span>")
			.replace(/\[color=red\]([\s\S]+?)\[\/color\]/g,"<span class='text_red'>$1</span>")
			.replace(/\[color=purple\]([\s\S]+?)\[\/color\]/g,"<span class='text_purple'>$1</span>")
			.replace(/\[color=blue\]([\s\S]+?)\[\/color\]/g,"<span class='text_blue'>$1</span>")
			.replace(/\[color=pink\]([\s\S]+?)\[\/color\]/g,"<span class='text_pink'>$1</span>")
			.replace(/\[color=black\]([\s\S]+?)\[\/color\]/g,"<span class='text_black'>$1</span>")
			.replace(/\[ul\]([\s\S]+?)\[\/ul\]/g,"<ul>$1</ul>")
			.replace(/[\s\n\r]*\[li\]([\s\S]+?)\[\/li\][\s\n\r]*/g,"<li>$1</li>")
			// urls
			.replace(/\[url=(.+?)\](.+?)\[\/url\]/g,"[link=$1]$2[/link]")
			.replace(/(.....)?(https?:\/\/)(www\.)?([^\/\s]+)?(\/?([^\t\r\n \()\[]*)?)/ig,function(str,linktag){
				if(linktag == "link=" || linktag == "[img=") return str;
				linktag = linktag || "";
				regx = new RegExp("^"+escape_regexp_str(linktag));
				var url = str.replace(regx,"");
				return linktag+"[link="+url+"]"+url+"[/link]";
			})
			.replace(/\[link=(.+?)\](.+?)\[\/link\]/g,function(str,link,text){
				var link_attr = "";
				if(link == text)
				{ // Link+text are the same
					// youtube video
					var youtube;
					var youtube_replace = "<div class='align_center'><iframe width='300' height='255' src='http://www.youtube.com/embed/$1' frameborder='0' allowfullscreen></iframe></div>";
					if(/https?:\/\/www\.youtube\.com\/watch\?v=([A-Za-z0-9\-\_]+)/.test(link))
					{
						youtube = link.replace(/https?:\/\/www\.youtube\.com\/watch\?v=([A-Za-z0-9\-\_]+)/,youtube_replace)
					}
					else if(/https?:\/\/youtu.be\/([A-Za-z0-9\-\_]+)/.test(link))
					{
						youtube = link.replace(/https?:\/\/youtu.be\/([A-Za-z0-9\-\_]+)/,youtube_replace);
					}
					if(youtube) return youtube;
					url = link;
					link_text = text.replace(/^https?:\/\/(www\.)?/,"");
					if(link_text.length > 50) link_text = link_text.substr(0,50)+"...";
					text_after ="";
				}
				else if(/^https?:\/\/.*?/i.test(link))
				{ // External link with "pretty" link text
					link_split = link.replace(/(https?:\/\/)(www\.)?([^\/\s]+)?(\/?(.*)?)/i,function(str,http,www,domain,uri){
						return domain;
					});
					url = link;
					link_text = text;
					text_after = " ["+link_split+"]";

				}
				else
				{ // Local link with "pretty" link text
					url = link.replace(/^javascript:/i,""); // xss security
					if(/^player/.test(url))
					{ // player_link
						var p = url.split(";");
						url = "/players/"+p[1]+"/";
						link_attr = " player_link='"+p[1]+"'";
					}
					else if(/^league/.test(url))
					{
						var l = url.split(";");
						url = "/league/"+l[1]+"/"+l[2]+"/"+l[3]+"/";
						link_attr = " league_link='"+l[1]+"' division='"+l[2]+"'";
					}
					link_text = text;
					text_after ="";
				}
				if(settings["link_disable"]) return link_text;
				return "<a href='"+url+"' title='"+url+"'"+link_attr+">"+link_text+"</a>"+text_after;
			})
			// @#club_id to link
			.replace(/@([0-9]+)/g,function(str,club_id){

				if(user_names[club_id]) name = user_names[club_id]["club_name"];
				else
				{
					name  = club_id;
					if(settings["ajax_content"]) settings["ajax_content"]["clubs"].push(club_id);
				}
				if(settings["link_disable"]) var club_link = "<span club_link='"+club_id+"'>"+name+"</span>";
				else var club_link = jqclublink({"id":club_id,"name":name,"auto_tooltip":true,"get_text":true});

				return "<span class='nowrap'>@"+club_link+"</span>"
			})
			// player_links
			.replace(/\[player=([0-9]+?)]/g,function(str,id){
				name = "@player"+id;
				if(settings["ajax_content"]) settings["ajax_content"]["players"].push(id);
				if(settings["link_disable"]) return "<span player_link='"+id+"'>"+name+"</span>";
				return jqplayerlink({"id":id,"name":name,"auto_tooltip":true,"get_text":true});
			})
			// Icons
			.replace(/\[img=([^\]]+?)\]/g,"<a href='$1'><img src='$1' /></a>")
			.replace(/\[smiley=([0-9])\]/g,"<span class='smiley smiley$1'></span>")
			.replace(/\[music\]/g,"#9834")
			.replace(/\[music2\]/g,"#9835")
			.replace(/\[music3\]/g,"#9836")
			.replace(/\[music4\]/g,"#9833")
			.replace(/\[flag=([a-z]+?)\]/g,function(str,f){
				return jqcountrylink({"country":f});
			})
			.replace(/\[money=([0-9]+?)]/g,function(str,m){
				return money(m);
			})
			.replace(/\[potential_stars=([0-9]+?)]/g,function(str,stars){
				return get_potential_stars(stars);
			})
			.replace(/\[flag=([a-z][a-z][a-z]?)]/g,function(str,country){
				return "<a href='/national-teams/"+country+"/'>"+get_flag(country)+"</a>";
			})

	}
	text = text
		.replace(/\[quote=(.*?)\]([\s\S]*?)\[\/quote\]/g,"<div class='quote'><div class='quote_text'><img src='/pics/forum/mega_quotes.png' class='float_left mega_quotes'/>$2</div><div class='subtle align_right'>- $1</div></div>");
	if(!settings["hide_styles"]) text = text.replace(/\[.+?\]/g,""); // Strip all bb tags not matched
	return text;
}
